
#import "MyDataService.h"
static  NSString *const SHNETWORIKINGGET             = @"GET";
static  NSString *const SHNETWORIKINGPOST            = @"POST";
static  NSString *const SHNETWORIKINGPUT             = @"PUT";
static  NSString *const SHNETWORIKINGDELETE          = @"DELETE";

#define LFJson(data)  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil]

@implementation MyDataService

#pragma mark - 初始化网络管理实例

//AF 3.0
+ (AFHTTPSessionManager *)manager{
    
    AFHTTPSessionManager *manager =[AFHTTPSessionManager manager];
    manager.requestSerializer = [AFJSONRequestSerializer serializer];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    // 设置超时时间
    [manager.requestSerializer willChangeValueForKey:@"timeoutInterval"];
    manager.requestSerializer.timeoutInterval = 20.f;
    [manager.requestSerializer didChangeValueForKey:@"timeoutInterval"];
    
    return manager;
}

#pragma mark - 检测url是否为空
+ (NSString *)checkUrlString:(NSString *)urlString{
    
    if (!urlString) {
        
        return @"";
        
    }else{
        return urlString;
    }
}

#pragma mark - 加密body
+ (NSDictionary *)encrencryptWithDictionary:(NSDictionary *)parameters{
    NSDictionary *body;
    
    if (!parameters) {
        body = @{};
        return body;
    }else{
        
        HBRSAHandler* handler = [[HBRSAHandler  alloc]init];
        body = [handler encrencryptWithDictionary:parameters];
    }
    
    return  body;
    
}

#pragma mark - 获取到最上层view
+ (UIView *)getTheWindowsOfLastSubViews{
    
    return [SHHelper currentViewController].view;
    
    
}


#pragma mark - 是否显示 loading
+ (void)isShowToast:(BOOL)isShowToast message:(NSString *)message  animated:(BOOL )animated{
    
    if (!message  && ![message isKindOfClass:[NSString class]]) {
        return;
    }
    UIView *view = [self getTheWindowsOfLastSubViews];
    if (isShowToast) {
        [view makeToast:message duration:2.f position:@"centet"];
    }
    
}

#pragma mark - RSA解密
+ (void)decryptWith:(id)responseObject complection:(void(^)(id result))successBlock {
    
    id result = LFJson(responseObject);
    
    if (!result) {
        
        [self isShowToast:YES message:@"数据解析失败！" animated:YES];
    }
    HBRSAHandler* handler = [[HBRSAHandler alloc]init];
    
    if ([result isKindOfClass:[NSDictionary class]] ) {
        
        BOOL  success = [result[@"success"] boolValue];
        
        if (success) {
            
            
            if (![result[@"data"] isKindOfClass:[NSDictionary class]]) {
                
                return;
                
            }
            NSDictionary *data = result[@"data"];
            if ([data objectForKey:@"msg"] &&[data objectForKey:@"signature"]) {//加密
                
                NSString *msg = result[@"data"][@"msg"];
                if (msg) {
                    msg = [handler decryptWithPrivatecKey:msg];
                    
                }
                
                if (([msg hasPrefix:@"{"] && [msg hasSuffix:@"}"]) || ([msg hasPrefix:@"["] && [msg hasSuffix:@"]"])){
                    NSDictionary *msgDict = [msg parseJSONStringToNSDictionary];
                    NSMutableDictionary *resultDict = [[NSMutableDictionary alloc]init];
                    [resultDict setValue:result[@"success"] forKey:@"success"];
                    [resultDict setValue:msgDict forKey:@"data"];
                    
                    successBlock(resultDict);
                    
                }else{
                    
                    NSMutableDictionary *resultDict = [[NSMutableDictionary alloc]init];
                    [resultDict setValue:result[@"success"] forKey:@"success"];
                    [resultDict setValue:msg forKey:@"data"];
                    successBlock(resultDict);
                }
                
                
            }else{
                successBlock(result);
                
                
            }
            
            
        }else{
            
            if ([result[@"data"] isKindOfClass:[NSString class]]) {
                
                if ([result[@"data"] isEqualToString:@"relogin"]) {
                    //
                    [UIApplication sharedApplication].keyWindow.rootViewController = [[UINavigationController alloc ]initWithRootViewController:[[JFLoginViewController alloc]init]];
                    
                }
                successBlock(result);
                
                
            }else{
                
                SHLog(@"返回数据格式不对！");
            }
            
            
            
            
        }
    }
    
    
    
    
    
}


#pragma mark -  兼容之前的网络请求
+ (void)requestAFURL:(NSString *)urlstring
          httpMethod:(NSString *)method
              params:(NSDictionary *)params
                data:(NSDictionary *)datas
         complection:(void(^)(id result))block failure:(void(^)(id erro))failureblock ;
{
    
    
    urlstring = [BASE_URL stringByAppendingString:urlstring];
    
    //AF 3.0
      AFHTTPSessionManager *manager = [self manager];
    
    if ([method isEqualToString:SHNETWORIKINGGET]) {

        // AF 3.0
        [manager GET:urlstring parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
            [self decryptWith:responseObject complection:^(id result) {
                
                block(result);
                
            }];
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [task cancel];
            failureblock(error);
            SHLog(@"异常:URL : ------\nERROR : %@  ",error);
            [self isShowToast:YES message:@"拼命链接中，稍等哈" animated:YES];
        }];
        
        
        
    }else if([method isEqualToString:SHNETWORIKINGPOST]) {
        
        
        NSDictionary *body =  [self encrencryptWithDictionary:params];
        
        // AF 3.0
        [manager POST:urlstring parameters:body progress:^(NSProgress * _Nonnull downloadProgress) {
            // 进度
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
            [task cancel];
            id result = LFJson(responseObject);
            
            if ((![result[@"data"] isKindOfClass:[NSDictionary class]]) && ([result[@"data"] isKindOfClass:[NSString class]])) {
                
                
                block(result);
                return ;
                
            }
            
            [self decryptWith:responseObject complection:^(id result) {
                block(result);
            }];
            
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [task cancel];
            failureblock(error);
            // 请求失败
            SHLog(@"异常:ERROR : %@  ",error);
            [self isShowToast:YES message:@"拼命链接中，稍等哈" animated:YES];
        }];
        
        
        
    }else if([method isEqualToString:SHNETWORIKINGPUT]){
        
        NSDictionary *body =   [self encrencryptWithDictionary:params];
        
       
        // AF 3.0
        [manager PUT:urlstring parameters:body success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
            [task cancel];
            [self decryptWith:responseObject complection:^(id result) {
                
                block(result);
            }];
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            block(error);
            // 请求失败
            SHLog(@"异常 ERROR : %@  ",error);
            [self isShowToast:YES message:@"拼命链接中，稍等哈" animated:YES];
        }];
        
        
    }else if([method isEqualToString:SHNETWORIKINGDELETE]){
        
      
        NSDictionary *body =   [self encrencryptWithDictionary:params] ;
      
        //AF 3.0
        [manager DELETE:urlstring parameters:body  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [task cancel];
            [self decryptWith:responseObject complection:^(id result) {
                
                block(result);
            }];
            
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            failureblock(error);
            // 请求失败
            SHLog(@"异常:URL : ERROR : %@  ",error);
            [self isShowToast:YES message:@"拼命链接中，稍等哈" animated:YES];
        }];
        
        
        
    }
    

}

#pragma mark --- -不需要RSA加密 解密
+ (void)requestNoRSAAFURL:(NSString *)urlstring
               httpMethod:(NSString *)method
                   params:(NSDictionary *)params
                     data:(NSDictionary *)datas
              complection:(void(^)(id result))block failure:(void(^)(id erro))failureblock{

    
    urlstring = [BASE_URL stringByAppendingString:urlstring];

    // AF3.0
     AFHTTPSessionManager *manager = [self manager];
    
    
    if ([method isEqualToString:SHNETWORIKINGGET]) {
        
       
        //AF 3.0
        [manager GET:urlstring parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
            id result = LFJson(responseObject);
            
            if (!result) {
                
                [self isShowToast:YES message:@"数据解析失败！" animated:YES];
            }
            
            [self showMsg:result];
            block(result);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [task cancel];
            failureblock(error);
            SHLog(@"异常:URL : ------\nERROR : %@  ",error);
            [self isShowToast:YES message:@"拼命链接中，稍等哈" animated:YES];
        }];
        
        
        
    }else if([method isEqualToString:SHNETWORIKINGPOST]) {
        
        
        // AF 3.0
        [manager POST:urlstring parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            // 进度
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
            [task cancel];
            id result = LFJson(responseObject);
            
            if (!result) {
                
                [self isShowToast:YES message:@"数据解析失败！" animated:YES];
            }
            
            [self showMsg:result];
            block(result);
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [task cancel];
            failureblock(error);
            // 请求失败
            SHLog(@"异常:ERROR : %@  ",error);
            [self isShowToast:YES message:@"拼命链接中，稍等哈" animated:YES];
        }];
        
        
        
    }else if([method isEqualToString:SHNETWORIKINGPUT]){
        
       
        // AF 3.0
        [manager PUT:urlstring parameters:params success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
            [task cancel];
            id result = LFJson(responseObject);
            
            if (!result) {
                
                [self isShowToast:YES message:@"数据解析失败！" animated:YES];
            }
            
            [self showMsg:result];
            block(result);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            failureblock(error);
            // 请求失败
            SHLog(@"异常 ERROR : %@  ",error);
            [self isShowToast:YES message:@"拼命链接中，稍等哈" animated:YES];
        }];
        
        
    }else if([method isEqualToString:SHNETWORIKINGDELETE]){
        
        
      
        //AF 3.0
        [manager DELETE:urlstring parameters:params  success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            [task cancel];
            id result = LFJson(responseObject);
            
            if (!result) {
                
                [self isShowToast:YES message:@"数据解析失败！" animated:YES];
            }
            
            [self showMsg:result];
            block(result);
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
            failureblock(error);
            // 请求失败
            SHLog(@"异常:URL : ERROR : %@  ",error);
            [self isShowToast:YES message:@"拼命链接中，稍等哈" animated:YES];
        }];
        
        
        
    }
    
    
    
    
}


+ (void)showMsg:(id)result{
    
    BOOL success = [result[@"success"] boolValue];
    
    if (!success) {
        
        if ([result[@"data"] isKindOfClass:[NSString class]]) {
            
            [[UIApplication sharedApplication].keyWindow makeToast:result[@"data"] duration:2 position:@"center"];
            
        }
    }
    
    
}
+ (void)showErro{
    
    [[UIApplication sharedApplication].keyWindow makeToast:@"拼命链接中，稍等哈" duration:1.5 position:@"center"];
    
    
}


#pragma mark - 接口重新定义，取消rsa加密，仅使用签名计算
/*
 １、取消rsa加密算法，仅使用签名计算
 
 ２、返回数据格式进行调整
 
 ３、对接口规范进行整理，凡是需要参数的接口均使用post方法，
 */

/*
+ (void)requestOnlySignAFURL:(NSString *)urlstring
                  httpMethod:(NSString *)method
                      params:(NSDictionary *)params
                        data:(NSDictionary *)datas
                 complection:(void (^)(id))block
                     failure:(void (^)(id))failureblock{
    
    urlstring = [BASE_URL stringByAppendingString:urlstring];
    
    
    AFHTTPSessionManager *manager = [self manager];
    
    if ([method isEqualToString:SHNETWORIKINGGET]) {
        
        [manager GET:urlstring parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            id result = LFJson(responseObject);
            
            if (!result) {
                
                [self isShowToast:YES message:@"数据解析失败！" animated:YES];
            }
            block(result);

            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [task cancel];
            failureblock(error);
            SHLog(@"异常:URL : ------\nERROR : %@  ",error);
            [self isShowToast:YES message:@"拼命链接中，稍等哈" animated:YES];
        }];
        
        
        
    }else if([method isEqualToString:SHNETWORIKINGPOST]) {
        
        
        NSDictionary *body =  [self createSignWithDictionary:params];
        [manager POST:urlstring parameters:body progress:^(NSProgress * _Nonnull downloadProgress) {
            // 进度
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            
            [task cancel];
            id result = LFJson(responseObject);
            if (!result) {
                
                [self isShowToast:YES message:@"数据解析失败！" animated:YES];
            }
            
            block(result);

            
            
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [task cancel];
            failureblock(error);
            // 请求失败
            SHLog(@"异常:ERROR : %@  ",error);
            [self isShowToast:YES message:@"拼命链接中，稍等哈" animated:YES];
        }];
         
        
    }
        
        
    
}

+ (NSDictionary *)createSignWithDictionary:(NSDictionary *)params{
    
    
    NSArray *allKeyArray = [params allKeys];
    NSArray *afterSortKeyArray = [allKeyArray sortedArrayUsingComparator:^NSComparisonResult(id  _Nonnull obj1, id  _Nonnull obj2) {
        NSComparisonResult resuest = [obj1 compare:obj2];
        return resuest ;//升序
    }];
    NSLog(@"afterSortKeyArray:%@",afterSortKeyArray);
    
    //通过排列的key值获取value
    NSMutableArray *valueArray = [NSMutableArray array];
    for (NSString *sortsing in afterSortKeyArray) {
        NSString *valueString = [params objectForKey:sortsing];
        [valueArray addObject:valueString];
    }
    NSLog(@"valueArray:%@",valueArray);
    
    NSMutableArray *signArray = [NSMutableArray array];
    for (int i = 0 ; i < afterSortKeyArray.count; i++) {
        NSString *keyValue = [NSString stringWithFormat:@"%@=%@",afterSortKeyArray[i],valueArray[i]];
        [signArray addObject:keyValue];
    }
    
    //signString用于签名的原始参数集合
    NSString *keyString = [signArray componentsJoinedByString:@"&"];
    NSString *signString = [NSString stringWithFormat:@"%@&%@",keyString,@"signkey=BECfeEA1c27c18A752F41CaC7cDce6b1"];
    NSLog(@"signString:%@",signString);
    NSMutableDictionary *body = [[NSMutableDictionary alloc]initWithDictionary:params];
    [body setValue:[signString md5] forKey:@"sign"];
    
    return  body;
}
*/

@end
